﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Net;
using rkShared.Serialization;
using rkShared.BEncode;

namespace rkShared.Net
{
    [Serializable]
    public class ClientInfo:IBinarySerializable
    {
        public ClientInfo()
        {
            IPHostEntry _he = Dns.GetHostByName(Dns.GetHostName());
            this.IPAddress = _he.AddressList[0].ToString();
        }
        public string NickName { get; set; }
        public string IPAddress { get; set; }
        public int Port { get; set; }
        public Vector3 ColorPreference { get; set; }
        public Guid ClientID { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;
            if (obj is ClientInfo)
            {
                return (obj as ClientInfo).ClientID.Equals(this.ClientID);
            }
            return false;
        }
        public override int GetHashCode()
        {
            return ClientID.GetHashCode();
        }
        #region IBinarySerializable Members

        /// <summary>
        /// Serializes ClientInfo object variables.
        /// </summary>
        /// <param name="dictionary"></param>
        public void SerializeToDictionary(rkShared.BEncode.BEncodedDictionary dictionary)
        {
            dictionary.Add("n", new BEncodedString(NickName, true));
            dictionary.Add("a", new BEncodedString(IPAddress, false));
            dictionary.Add("p", this.Port);

            BEncodedDictionary _vector = new BEncodedDictionary();
            this.ColorPreference.SerializeToDictionary(_vector);
            dictionary.Add("v", _vector);
            dictionary.Add("c", new BEncodedString(this.ClientID.ToString()));
        }

        public void DeserializeFromDictionary(rkShared.BEncode.BEncodedDictionary dict)
        {
            this.NickName = Encoding.Unicode.GetString((dict["n"] as BEncodedString).Value);
            this.IPAddress = Encoding.ASCII.GetString((dict["a"] as BEncodedString).Value);
            this.Port = (dict["p"] as BEncodedInt).IntValue;
            this.ColorPreference = new Vector3();
            this.ColorPreference.DeserializeFromDictionary(dict["v"] as BEncodedDictionary);
            this.ClientID = new Guid(Encoding.ASCII.GetString((dict["c"] as BEncodedString).Value));
        }

        #endregion
    }
}
